<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Use correct character set. -->
  <meta charset="utf-8">
  <!-- Tell IE to use the latest, best version. -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <title>Hello Miami Tiles!</title>
  <!-- CodeMirror在线代码编辑器 -->
  <script src="js/codemirror-5.19.0/lib/codemirror.js"></script>
  <script src="js/codemirror-5.19.0/addon/display/autorefresh.js"></script>
  <link rel="stylesheet" href="js/codemirror-5.19.0/lib/codemirror.css">
  <script src="js/codemirror-5.19.0/mode/javascript/javascript.js"></script>
  <!-- Bootstrap样式css -->
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="js/bootstrap-colorpicker-master/dist/css/bootstrap-colorpicker.min.css">
  <!-- Cesium库 -->
  <script src="Cesium/Cesium.js"></script>
  <!-- JQuery库 -->
  <script src="js/jquery-2.1.1.min.js"></script>
  <style>
      @import url(Cesium/Widgets/widgets.css);
      html, body, #cesiumContainer {
          width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
      }
  </style>
</head>
<body>
  <div id="cesiumContainer"></div>
  <!-- Modal -->
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	  <div class="modal-dialog">
		<div class="modal-content">
		  <div class="modal-header">
			<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
			<h4 class="modal-title" id="myModalLabel">声明样式</h4>
			<div id="cp2" class="input-group colorpicker-component">
				<input type="text" class="form-control" placeholder="颜色提示..."/>
				<span class="input-group-addon"><i></i></span>
			</div>
		  </div>
		  <div class="modal-body">
			<textarea id="editor"></textarea>
		  </div>
		  <div class="modal-footer">
			<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
			<button type="button" class="btn btn-primary" onclick="saveStyle()">应用</button>
		  </div>
		</div>
	  </div>
	</div>
</body>
<script>
	$(function() {
        $('#cp2').colorpicker();
    });
	var myTextArea = document.getElementById("editor");

	var json = {"color" : {
						"conditions" : {	
							"${height} >= 200" : "color('#ffe5cc')",
							"${height} >= 150" : "color('#ffffcc')",
							"${height} >= 100" : "color('#e5ffcc')",
							"${height} >= 50" : "color('#ccffcc')",
							"${height} >= 20" : "color('#ccffe5')",
							"${height} >= 10" : "color('#ccffff')",
							"true" : "color('#cce5ff')"
						}
					}
				};
	var text1 = JSON.stringify(json,null,2);
	var myCodeMirror = CodeMirror.fromTextArea(myTextArea,{
		autoRefresh:true,
		mode:  "application/json",
		lineNumbers: true,
		autofocus:true
	});
	myCodeMirror.setValue('//当前样式:随高度改变颜色\n'+text1);
	
	function saveStyle(){
		var content = myCodeMirror.getValue();
		var index = content.indexOf('{');
		content = content.slice(index);
		console.log(content);
		var color = JSON.parse(content);
		console.log(color);
		tileset.style = new Cesium.Cesium3DTileStyle(color);
	}
	
    var osm = Cesium.createOpenStreetMapImageryProvider({
		url : 'https://a.tile.openstreetmap.org/'
	});
	var viewer = new Cesium.Viewer('cesiumContainer', {
		scene3DOnly : true,
		baseLayerPicker:false,
		imageryProvider:osm,
		vrButton:true
	});
	
	var btn = document.createElement('button');
	btn.setAttribute('type','button');
	btn.setAttribute('title','Style');
	btn.setAttribute('data-toggle','modal');
	btn.setAttribute('data-target','#myModal');
	btn.setAttribute('class','cesium-button cesium-toolbar-button');
	document.getElementsByClassName('cesium-viewer-toolbar')[0].appendChild(btn);
	
	viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function(commandInfo){
		//Zoom to custom extent
		viewer.camera.flyTo({
			destination : new Cesium.Cartesian3(978703.4032039205, -5664709.285048889, 2754627.305272117),
			orientation : {
				direction : new Cesium.Cartesian3(0.33506436388093397, 0.7178758873584659, 0.6102344487214404),
				up : new Cesium.Cartesian3(0.27649053726026684, -0.6940744040291643, 0.6646906833084766)
			}
		});		
		//Tell the home button not to do anything.
		commandInfo.cancel = true;
	});
	var scene = viewer.scene;
	scene.fog.enabled = false;
	scene.debugShowFramesPerSecond = true;

	var dataurl = "./data/"
	var tileset;
	
	function loadTileset(url) {
		reset();

		tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
			url : url,
			debugShowStatistics : true,
			maximumNumberOfLoadedTiles : 3
		}));

		return tileset.readyPromise.then(function(tileset) {
			// var boundingSphere = tileset.boundingSphere;
			// viewer.camera.viewBoundingSphere(boundingSphere, new Cesium.HeadingPitchRange(0, -2.0, 0));
			// viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
			viewer.camera.setView({
				destination : new Cesium.Cartesian3(978703.4032039205, -5664709.285048889, 2754627.305272117),
				orientation : {
					direction : new Cesium.Cartesian3(0.33506436388093397, 0.7178758873584659, 0.6102344487214404),
					up : new Cesium.Cartesian3(0.27649053726026684, -0.6940744040291643, 0.6646906833084766)
				}
			});	
			var properties = tileset.properties;
			if (Cesium.defined(properties) && Cesium.defined(properties.height)) {
				tileset.style = new Cesium.Cesium3DTileStyle({
	//              "color" : "color('#BAA5EC')",
	//              "color" : "color('cyan', 0.5)",
	//              "color" : "rgb(100, 255, 190)",
	//              "color" : "hsla(0.9, 0.6, 0.7, 0.75)",
					"color" : {
						"conditions" : {	
							"${height} >= 200" : "color('#ffe5cc')",
							"${height} >= 150" : "color('#ffffcc')",
							"${height} >= 100" : "color('#e5ffcc')",
							"${height} >= 50" : "color('#ccffcc')",
							"${height} >= 20" : "color('#ccffe5')",
							"${height} >= 10" : "color('#ccffff')",
							"true" : "color('#cce5ff')"
						}
					},
	//              "show": false
	//              "show" : "${Height} >= 0",
					"meta" : {
						"description" : "'Building id ${id} has height ${height}.'"
					}
				});
				// addStyleUI();
			}

			tileset.loadProgress.addEventListener(function(numberOfPendingRequests, numberProcessing) {
				if ((numberOfPendingRequests === 0) && (numberProcessing === 0)) {
					//console.log('Stopped loading');
					return;
				}

				//console.log('Loading: requests: ' + numberOfPendingRequests + ', processing: ' + numberProcessing);
			});

			tileset.tileUnload.addEventListener(function(tile) {
				//console.log('Tile unloaded.')
			});
		});
	}


	var canvas = viewer.canvas;
	canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
	canvas.onclick = function() {
		// To get key events
		canvas.focus();
	};

	var handler = new Cesium.ScreenSpaceEventHandler(canvas);

	var pickingEnabled = true;
	var flags = {
		// Mouse
		leftDown : false,
		middleDown : false,
		rightDown : false,

		annotate : false
	};

	handler.setInputAction(function(movement) {
		flags.leftDown = true;
	}, Cesium.ScreenSpaceEventType.LEFT_DOWN);

	handler.setInputAction(function(movement) {
		flags.middleDown = true;
	}, Cesium.ScreenSpaceEventType.MIDDLE_DOWN);

	handler.setInputAction(function(movement) {
		flags.rightDown = true;
	}, Cesium.ScreenSpaceEventType.RIGHT_DOWN);

	handler.setInputAction(function(movement) {
		flags.leftDown = false;
	}, Cesium.ScreenSpaceEventType.LEFT_UP);

	handler.setInputAction(function(movement) {
		flags.middleDown = false;
	}, Cesium.ScreenSpaceEventType.MIDDLE_UP);

	handler.setInputAction(function(movement) {
		flags.rightDown = false;
	}, Cesium.ScreenSpaceEventType.RIGHT_UP);

	document.addEventListener('keyup', function(e) {
		if (e.keyCode === 'W'.charCodeAt(0)) {
			flags.annotate = !flags.annotate;
		}
	}, false);

	var current = {
		feature : undefined,
		originalColor : new Cesium.Color()
	};

	var HIGHLIGHT_COLOR = new Cesium.Color(1.0, 1.0, 0.0, 0.4);

	// Highlight feature on mouse over
	handler.setInputAction(function(movement) {
		if (!pickingEnabled) {
			return;
		}

		if (flags.leftDown || flags.middleDown || flags.rightDown) {
			// Don't highlight when panning and zooming
			return;
		}

		var pickedFeature = scene.pick(movement.endPosition);
		if (Cesium.defined(current.feature) && (current.feature !== pickedFeature)) {
			// Restore original color to feature that is no longer selected

			// This assignment is necessary to work with the set property
			current.feature.color = Cesium.Color.clone(current.originalColor, current.feature.color);
			current.feature = undefined;
		}

		if (Cesium.defined(pickedFeature) && (pickedFeature !== current.feature)) {
	// For testing re-evaluating a style when a property changes
	//      pickedFeature.setProperty('id', 1);

			current.feature = pickedFeature;
			Cesium.Color.clone(pickedFeature.color, current.originalColor);

			// Highlight newly selected feature
			pickedFeature.color = Cesium.Color.clone(HIGHLIGHT_COLOR, pickedFeature.color);
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	var annotations = scene.primitives.add(new Cesium.LabelCollection());

	var infobox = new Cesium.Entity('Title to put in the infobox');
	
	handler.setInputAction(function(movement) {
		if (!pickingEnabled) {
			return;
		}

		var feature = current.feature;
		if (Cesium.defined(feature)) {
			var str = '';
			viewer.entities.remove(infobox);
			var properties = feature.primitive.properties; // get properties from tileset
			if (Cesium.defined(properties)) {
				for (var name in properties) {
					if (properties.hasOwnProperty(name)) {
						console.log(name + ': ' + feature.getProperty(name));
						str=str+'<tr><th style="width:120px;font-weight:bold;">'+name+'</th><th style="font-weight:normal;">'+feature.getProperty(name)+'</th></tr>'
					}
				}
			}

			var title = feature.getProperty('name');
			var tid = feature.getProperty('TARGET_FID');
			infobox.name = (title!=' ')?(title):(tid);
			infobox.description = {
				getValue : function() {
					return '<table style="text-align:left">'+str+'</table>';
				}
			};
			viewer.entities.add(infobox);
			viewer.selectedEntity = infobox;
			// evaluate feature description
			if (Cesium.defined(tileset.style.meta.description)) {
				console.log("Description : " + tileset.style.meta.description.evaluate(feature));
			}

			feature.setProperty('clicked', true);
			
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	handler.setInputAction(function(movement) {
		if (!pickingEnabled) {
			return;
		}

		if (flags.annotate) {
			// Add annotation showing the height at the click location
			annotate(movement);
		} else {
			// When a feature is double clicked, zoom to it
			zoom(movement);
		}
	}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

	function annotate(movement) {
		if (Cesium.defined(current.feature) && scene.pickPositionSupported) {
			var cartesian = scene.pickPosition(movement.position);
			var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
			var height = cartographic.height.toFixed(2) + ' m';

			annotations.add({
				position : cartesian,
				text : height,
				horizontalOrigin : Cesium.HorizontalOrigin.LEFT,
				verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
				eyeOffset : new Cesium.Cartesian3(0.0, 0.0, -1.0)
			});
		}
	}

	function offsetFromHeadingPitchRange(heading, pitch, range) {
		pitch = Cesium.Math.clamp(pitch, -Cesium.Math.PI_OVER_TWO, Cesium.Math.PI_OVER_TWO);
		heading = Cesium.Math.zeroToTwoPi(heading) - Cesium.Math.PI_OVER_TWO;

		var pitchQuat = Cesium.Quaternion.fromAxisAngle(Cesium.Cartesian3.UNIT_Y, -pitch);
		var headingQuat = Cesium.Quaternion.fromAxisAngle(Cesium.Cartesian3.UNIT_Z, -heading);
		var rotQuat = Cesium.Quaternion.multiply(headingQuat, pitchQuat, headingQuat);
		var rotMatrix = Cesium.Matrix3.fromQuaternion(rotQuat);

		var offset = Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X);
		Cesium.Matrix3.multiplyByVector(rotMatrix, offset, offset);
		Cesium.Cartesian3.negate(offset, offset);
		Cesium.Cartesian3.multiplyByScalar(offset, range, offset);
		return offset;
	}

	function zoom(movement) {
		var feature = current.feature;
		if (Cesium.defined(feature)) {
			var longitude = feature.getProperty('Longitude');
			var latitude = feature.getProperty('Latitude');
			var height = feature.getProperty('Height');

			if (!Cesium.defined(longitude) || !Cesium.defined(latitude) || !Cesium.defined(height)) {
				return;
			}

			var positionCartographic = new Cesium.Cartographic(longitude, latitude, height * 0.5);
			var position = scene.globe.ellipsoid.cartographicToCartesian(positionCartographic);

			var camera = scene.camera;
			var heading = camera.heading;
			var pitch = camera.pitch;

			var offset = offsetFromHeadingPitchRange(heading, pitch, height * 2.0);

			var transform = Cesium.Transforms.eastNorthUpToFixedFrame(position);
			Cesium.Matrix4.multiplyByPoint(transform, offset, position);

			camera.flyTo({
				destination : position,
				orientation : {
					heading : heading,
					pitch : pitch
				},
				easingFunction : Cesium.EasingFunction.QUADRATIC_OUT
			});
		}
	}

	//When a feature is double middle clicked, hide it
	// handler.setInputAction(function(movement) {
		// if (!pickingEnabled) {
			// return;
		// }

		// if (Cesium.defined(current.feature)) {
			// current.feature.show = false;
		// }
	// }, Cesium.ScreenSpaceEventType.MIDDLE_DOUBLE_CLICK);

	///////////////////////////////////////////////////////////////////////////////

	
	// Styling ////////////////////////////////////////////////////////////////////

	var styleElements = [];
	var numberofColors = 6;
	var currentPropertyName = 'Height';

	function getRandomColor() {
		var color = Cesium.Color.fromRandom();
		color.alpha = 1.0;
		return color.toCssColorString();
	}

	function styleFunction(name) {
		var conditions = {};
		var intervalSize = Math.floor(100/numberofColors);
		for (var i = numberofColors; i >= 0; --i) {
			var cond = '${' + name + '} > ' + (i * intervalSize);
			conditions[cond] = getRandomColor();
		}
		conditions['true'] = getRandomColor();

		tileset.style = new Cesium.Cesium3DTileStyle({
			color : {
				conditions : conditions
			},
			show : '${' + name + '} >= 0'
		});

		currentPropertyName = name;
	}

	function getStyleFunction(name) {
		return function() {
			styleFunction(name);
		};
	}

	function reset() {
		if (Cesium.defined(tileset)) {
			scene.primitives.remove(tileset);
		}

		// // Remove style UI for the previous tileset
		// var buttonsLength = styleElements.length;
		// for (var i = 0; i < buttonsLength; ++i) {
			// var element = styleElements[i];
			// element.parentNode.removeChild(element);
		// }
		// styleElements = [];
		// numberofColors = 6;

		// current.feature = undefined;
		// current.originalColor = new Cesium.Color();

		// annotations.removeAll();
	}
	loadTileset(dataurl);
	///////////////////////////////////////////////////////////////////////////////
	

  </script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-colorpicker-master/dist/js/bootstrap-colorpicker.min.js"></script>
</html>